#include "dlgeditcost.h"
#include "pmclientdata.h"
#include "main.h"
#include "pm/manager.h"
#include "pm/task.h"
#include <boost/foreach.hpp>

DlgEditCost::DlgEditCost(wxWindow* parent, const wxString& title)
: DlgEditCostGui(parent, wxID_ANY, title)
{
	pm::GetTasksByProject crit(wxGetApp().GetActiveProject());
	pm::select(crit);
	BOOST_FOREACH(const pm::Task& task, crit.m_result) {
		m_listTask->Append(task.name(), new IdClientData(task.id()));
	}
	m_listTask->SetSelection(0);
}

void DlgEditCost::OnSubmit( wxCommandEvent& WXUNUSED(event) )
{
	if (TransferDataFromWindow() == false) {
		return;
	}
	
	double unitCost = 0;
	double quantity = 0;
	if (!m_sUnitCost.ToDouble(&unitCost) || !m_sQuantity.ToDouble(&quantity)) {
		return;
	}
	
	const IdClientData* data = dynamic_cast<IdClientData*>(m_listTask->GetClientObject(m_listTask->GetSelection()));
	assert(data);
	
	m_cost.name(m_editName->GetValue());
	m_cost.unit_cost(unitCost);
	m_cost.quantity(quantity);
	m_cost.date(m_dpDate->GetValue());
	m_cost.id_task(data->id());
	
	EndModal(Submit() ? wxID_OK : wxID_CANCEL);
}

DlgNewCost::DlgNewCost(wxWindow* parent)
: DlgEditCost(parent, _("New cost"))
{
}

bool DlgNewCost::Submit()
{
	if (pm::insert(m_cost) == false) {
		wxLogError(_("Can't insert cost !"));
		return false;
	}
	
	pmEvent<pm::Cost> evt(pmEVT_COST_ADDED, m_cost);
	wxPostEvent(wxTheApp, evt);
	return true;
}

DlgUpdateCost::DlgUpdateCost(wxWindow* parent, const pm::Cost& cost)
: DlgEditCost(parent, _("Update cost"))
{
	m_cost = cost;
	
	m_editName->SetValue(m_cost.name());
	m_sUnitCost.Printf(wxT("%.2f"), m_cost.unit_cost());
	m_sQuantity.Printf(wxT("%.2f"), m_cost.quantity());
	m_dpDate->SetValue(m_cost.date());
	// TODO : select project
	TransferDataToWindow();
}

bool DlgUpdateCost::Submit()
{
	if (pm::update(m_cost) == false) {
		wxLogError(_("Can't update cost !"));
		return false;
	}
	
	pmEvent<pm::Cost> evt(pmEVT_COST_UPDATED, m_cost);
	wxPostEvent(wxTheApp, evt);
	return true;
}
